﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using jSLApp.Client.ApplicationBase;
using jSLApp.Client.MainService;
using jSLCore.Client.Presentation.BaseControl.Selection;
using Telerik.Windows.Controls.GridView;

namespace jSLApp.Client.Forms
{
    public partial class FilmList : SelectControl
    {
        private readonly string _keyWord;
        public FilmList(string keyWord=null)
        {
            _keyWord = keyWord;
            InitializeComponent();

            txt.Value = _keyWord ?? "";
        }

        #region dialog

        public override ISelectableGrid GetSelectableGrid()
        {
            return grid;
        }

        public override bool IsStandartOkCancelEnabledWhenNotSelectable
        {
            get { return false; }
        }

        protected override void AcceptButtonClicked()
        {
            Search();
        }

        private void Search()
        {
            var selectedGenreId = genreGrid.SelectedItem!=null?((Genre)genreGrid.SelectedItem).id:(int?)null;

            DoWork("Поиск",(sender, args) =>
                               {
                                   args.Result = Communication.Proxy.SearchFilms(args.String, (bool) args.Params[1],
                                                                                 (int?) args.Params[2]);
                               },(o, eventArgs) =>
                                     {
                                         result = (int[]) eventArgs.Result;
                                         DontLoadAnythingElse();
                                         cursor = 0;
                                         resultAbout.Text = string.Format("Найдено записей: {0}", result.Length);
                                         loadAllButton.Visibility=Visibility.Visible;
                                         Films = new ObservableCollection<Film>();
                                         ShowNextPage();
                                     },txt.Value,ch.IsChecked,selectedGenreId);
        }

        private void DontLoadAnythingElse()
        {
            lastIdToLoad = -1;
            loadAllButton.Visibility=Visibility.Collapsed;
        }

        private void LoadAll_Clicked(object sender, RoutedEventArgs e)
        {
            ShowNextPage(result.Length-cursor,false);
        }

        private void ShowNextPage(int pageSize=15,bool dontShowSplashScreen = true)
        {
            //const int pageSize = 15;
            var count = Math.Min(pageSize, result.Length - cursor);
            
            var ids = result.Skip(cursor).Take(count).ToArray();

            if (ids.Count() == 0) DontLoadAnythingElse();
            else
            {
                lastIdToLoad = ids.ElementAt(ids.Count() - 1);
            }

            cursor += pageSize;

            if (cursor >= result.Length) DontLoadAnythingElse();

            VisualStateManager.GoToState(this, "Loading", true);
            DoWork(dontShowSplashScreen, (sender, args) =>
                            {
                                args.Result = Communication.Proxy.GetFilms((int[]) args.Params[0]);
                            },(o, eventArgs) =>
                                  {
                                      var films = (IEnumerable<Film>)eventArgs.Result;
                                      foreach (var film in films)
                                      {
                                          Films.Add(film);
                                      }
                                      VisualStateManager.GoToState(this, "Ready", true);
                                  },ids,0);

            
        }

        ObservableCollection<Film> Films
        {
            get { return (ObservableCollection<Film>) grid.ItemsSource; }
            set { grid.ItemsSource = value; }
        }

        private int[] result;
        private int cursor;
        private int lastIdToLoad;

        private void genreName_Loaded(object sender, RowLoadedEventArgs rowLoadedEventArgs)
        {
            if (rowLoadedEventArgs.DataElement != null)
            {
                var filmId = ((Film)rowLoadedEventArgs.DataElement).id;

                if (filmId == lastIdToLoad)
                    ShowNextPage();
            }
        }

        public override void LoadInitialData()
        {
            DoWork("Загрузка жанров",(sender, args) =>
                                         {
                                             args.Result = Communication.Proxy.GetGenres();
                                         },(o, eventArgs) =>
                                                               {
                                                                   if(eventArgs.Error==null)
                                                                   {
                                                                       genreGrid.ItemsSource = eventArgs.Result;
                                                                   }
                                                               });

            Search();
        }

        public override Control GetControlForInitialFocus()
        {
            return txt;
        }

        #endregion

        private void goFilm_Clicked(object sender, RowSelectedEventArgs e)
        {
            var film = (Film)e.RowObject;
            MainContentContainer.Current.ShowFilm(film.id);
        }


        private void genre_Changed(object sender, EventArgs e)
        {
            Search();
        }

        private void allGenres_Clicked(object sender, RoutedEventArgs e)
        {
            genreGrid.SelectedItem = null;
        }
    }
}
